package com.ruihang.generalibrary.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by rh008 on 2017/7/26.
 */

public class PermissionUtils {

    public static String[] checkPermissions(Activity context, List<String> canRequest, String... permissions) {
        if (permissions == null || permissions.length == 0) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ActivityCompat.checkSelfPermission(context, permissions[i]) != PermissionChecker.PERMISSION_GRANTED) {
                if (canRequest != null) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(context, permissions[i])) {
                        canRequest.add(permissions[i]);
                    }
                }
                list.add(permissions[i]);
            }

        }
        if (list.size() > 0) {
            String[] ss = new String[list.size()];
            list.toArray(ss);
            return ss;
        } else {
            return null;
        }
    }

    public static String[] checkPermissions(Activity context, String... permissions) {
        return checkPermissions(context,null,permissions);
    }

    public static void toSetting(Activity activity, int requestCode) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS
                , Uri.parse("package:" + activity.getPackageName()));
        activity.startActivityForResult(intent, requestCode);
    }

}
